#include <bits/stdc++.h>
using namespace std;

int n, m, q, a[6][100005], b[6][100005];
struct node {
    int p[6];
    node(int x)
    {
        for (int i = 1; i <= m; i++)
            p[i] = b[i][x];
    }
    node(const node& a, const node& b)
    {
        for (int i = 1; i <= m; i++)
            p[i] = min(a.p[i], b.p[i]);
    }
    node()
    {
    }
    bool operator>(const node& b)
    {
        for (int i = 1; i <= m; i++)
            if (p[i] <= b.p[i])
                return false;
        return true;
    }
} f[20][100005], g[6][100005];

int main()
{
    cin >> n >> m;
    for (int i = 1; i <= m; i++)
        for (int j = 1; j <= n; j++)
            cin >> a[i][j], b[i][a[i][j]] = j;
    for (int i = 1; i <= m; i++) {
        for (int j = n; j >= 1; j--) {
            g[i][j] = node(a[i][j]);
            if (j != n)
                g[i][j] = node(g[i][j], g[i][j + 1]);
        }
    }
    for (int i = 1; i <= n; i++) {
        f[0][i] = g[1][b[1][i]];
        for (int j = 2; j <= m; j++)
            f[0][i] = node(f[0][i], g[j][b[j][i]]);
    }
    for (int i = 1; i <= 19; i++)
        for (int j = 1; j <= n; j++) {
            f[i][j] = f[i - 1][j];
            for (int k = 1; k <= m; k++)
                f[i][j] = node(f[i][j], f[i - 1][a[k][f[i - 1][j].p[k]]]);
        }
    cin >> q;
    while (q--) {
        int x, y;
        cin >> x >> y;
        node A(x), B(y);
        if (A > B) {
            int ans = 0;
            for (int i = 19; i >= 0; i--) {
                node nxt = A;
                for (int j = 1; j <= m; j++)
                    nxt = node(nxt, f[i][a[j][A.p[j]]]);
                if (nxt > B)
                    ans += 1 << i, A = nxt;
            }
            if (ans > n)
                cout << -1 << endl;
            else
                cout << ans + 2 << endl;
        } else
            cout << 1 << endl;
    }
    return 0;
}